import Vue from "vue"
import CryptoJS from 'crypto-js'

// 默认的 KEY 与 iv 如果没有给
const KEY = CryptoJS.enc.Utf8.parse("1234567890123456");
const IV = CryptoJS.enc.Utf8.parse('1234567890123456');
/**
 * AES加密 ：字符串 key iv  返回base64
 */

export default {
  Encrypt(word, keyStr, ivStr) {
    let key = KEY
    let iv = IV

    if (keyStr) {
      key = CryptoJS.enc.Utf8.parse(keyStr);
      iv = CryptoJS.enc.Utf8.parse(ivStr);
    }

    let srcs = CryptoJS.enc.Utf8.parse(word);
    var encrypted = CryptoJS.AES.encrypt(srcs, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    });
    // console.log("-=-=-=-", encrypted.ciphertext)
    return CryptoJS.enc.Base64.stringify(encrypted.ciphertext);

  },

  Decrypt(word, keyStr) {
    let key = KEY
    let iv = IV
    if (keyStr) {
      key = CryptoJS.enc.Utf8.parse(keyStr);
    }

    let base64 = CryptoJS.enc.Base64.parse(word);
    let src = CryptoJS.enc.Base64.stringify(base64);

    var decrypt = CryptoJS.AES.decrypt(src, key, {
      iv: iv,
      mode: CryptoJS.mode.CBC,
      padding: CryptoJS.pad.ZeroPadding
    });

    var decryptedStr = decrypt.toString(CryptoJS.enc.Utf8);
    return decryptedStr.toString();
  },
//   var result = document.getElementById("result");
// var file = document.getElementById("file");
//
// //判断浏览器是否支持FileReader接口
// if (typeof FileReader == 'undefined') {
//   result.InnerHTML = "<p>你的浏览器不支持FileReader接口！</p>";
//   //使选择控件不可操作
//   file.setAttribute("disabled", "disabled");
// }

  encryption() {
    //读取文件
    var file = document.getElementById("file").files[0];
    var reader = new FileReader();
    //将文件以arraybuffer形式读入页面
    reader.readAsArrayBuffer(file);
    reader.onload = (e)
    {
      alert(0);
      var result = document.getElementById("result");
      //分块加密文件;自定义块长度
      var blk = 1024;//blk=1024B
      var enc = encryptabbyblock(this.result, blk);
      dosave(enc, "text/latex", "enc.txt");//dosave()将加密文件存储为enc.txt
    }
  },

  decryption() {
    //读取文件
    var file = document.getElementById("file").files[0];
    var reader = new FileReader();
    //将文件以arraybuffer形式读入页面
    reader.readAsArrayBuffer(file);
    reader.onload = (e)
    {
      var result = document.getElementById("result");
      //分块解密文件;自定义块长度
      var blk = 1024;//blk=1024B
      var enc = decryptabbyblock(this.result, blk);
      dosave(enc, "text/latex", "dec.txt");//dosave()将加密文件存储为dec.txt
    }
  },

  encryptiontext() {
    //读取文件
    var file = document.getElementById("file").files[0];
    var reader = new FileReader();
    //将文件以text形式读入页面
    reader.readAsText(file);
    reader.onload = (e)
    {
      alert(0);
      var result = document.getElementById("result");
      //分块加密文件;自定义块长度
      var blk = 1024;//blk=1024B
      var enc = encryptbyblock(this.result, blk);
      dosave(enc, "text/latex", "enct.txt");//dosave()将加密文件存储为enc.txt
    }
  },

  decryptiontext() {
    //读取文件
    var file = document.getElementById("file").files[0];
    var reader = new FileReader();
    //将文件以text形式读入页面
    reader.readAsText(file);
    reader.onload = (e)
    {
      var result = document.getElementById("result");
      //分块解密文件;自定义块长度
      var blk = 1024;//blk=1024B
      var enc = decryptbyblock(this.result, blk);
      dosave(enc, "text/latex", "dect.txt");//dosave()将加密文件存储为dec.txt
    }
  },

  decryptbyblock(text, blk) {
    var key = CryptoJS.enc.Latin1.parse('1234567890123456');
    var iv = CryptoJS.enc.Latin1.parse('1234567890123456');
    var res = '';
    var len = text.length;
    var n = Math.floor(len / blk);
    for (var i = 0; i <= n; i++) {
      var end = (i < n) ? blk : len % blk;
      var tmp = text.substr(i * blk, end);
      tmp.length = end;
      var tmp_w = CryptoJS.enc.Latin1.parse(tmp);
      //alert(tmp_w);
      var b64 = CryptoJS.enc.Base64.stringify(tmp_w);
      var tmp_ens = CryptoJS.AES.decrypt(b64, key, {iv: iv, mode: CryptoJS.mode.CFB, padding: CryptoJS.pad.NoPadding});
      res += tmp_ens;
    }
    return res;
  },

  encryptbyblock(text, blk) {
    var key = CryptoJS.enc.Latin1.parse('1234567890123456');
    var iv = CryptoJS.enc.Latin1.parse('1234567890123456');
    var res = '';
    var len = text.length;
    var n = Math.floor(len / blk);
    for (var i = 0; i < n; i++) {
      var end = (i < n) ? blk : len % blk;
      var tmp = text.substr(i * blk, end);
      var tmp_w = CryptoJS.enc.Latin1.parse(tmp);
      var tmp_ens = CryptoJS.AES.encrypt(tmp_w, key, {
        iv: iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding
      });
      var lartinens = CryptoJS.enc.Latin1.stringify(tmp_ens.ciphertext);
      //res+=lartinens;
      rh(res, lartinens);
    }
    return res;
  },

  encryptabbyblock(arraybuffer, blk) {
    var key = CryptoJS.enc.Latin1.parse('1234567890123456');
    var iv = CryptoJS.enc.Latin1.parse('1234567890123456');
    var len = arraybuffer.byteLength;
    var n = Math.floor(len / blk);
    var encryption = new Uint8Array(arraybuffer.byteLength);
    for (var i = 0; i <= n; i++) {
      alert(0);
      var end = (i < n) ? blk : len % blk;
      var new_bufer = new ArrayBuffer(end);
      new_bufer = arraybuffer.slice(i * blk, i * blk + end);

      var barray = new Uint8Array(new_bufer);
      var wbuf = CryptoJS.enc.u8array.parse(barray);
      var encrypted = CryptoJS.AES.encrypt(wbuf, key, {
        iv: iv,
        mode: CryptoJS.mode.CFB,
        padding: CryptoJS.pad.NoPadding
      });
      var encrypted_unit8arr = CryptoJS.enc.u8array.stringify(encrypted.ciphertext);
      encryption.set(encrypted_unit8arr, i * blk);
    }
    return encryption;
  },

  decryptabbyblock(arraybuffer, blk, key) {
    var reader = new FileReader();
    var result
    var final
    //将文件以arraybuffer形式读入页面
    reader.readAsBinaryString(arraybuffer);
    result = reader.result
    var key = CryptoJS.enc.Latin1.parse(key);
    // var iv = CryptoJS.enc.Latin1.parse('1234567890123456');
    var len = result.byteLength;
    var n = Math.floor(len / blk);
    var encryption = new Uint8Array(result.byteLength);
    for (var i = 0; i <= n; i++) {
      var end = (i < n) ? blk : len % blk;
      var new_bufer = new ArrayBuffer(end);
      new_bufer = arraybuffer.slice(i * blk, i * blk + end);
      var barray = new Uint8Array(new_bufer);

      var wbuf = CryptoJS.enc.u8array.parse(barray);
      var b64 = CryptoJS.enc.Base64.stringify(wbuf);
      var decrypted = CryptoJS.AES.decrypt(b64, key, {
        // iv: iv,
        // mode: CryptoJS.mode.CFB,
        // padding: CryptoJS.pad.NoPadding
        mode: CryptoJS.mode.ECB,
        padding: CryptoJS.pad.Pkcs7
      });
      var decrypted_unit8arr = CryptoJS.enc.u8array.stringify(decrypted);
      encryption.set(decrypted_unit8arr, i * blk);
    }
    final = reader.readAsArrayBuffer(encryption)
    return fanal;
  },

  rh(word1, word2) {
    if (word1 == '') {
      alert(0);
      return word2;
    } else {
      var uw1 = word1.words;
      var uw2 = word2.words;

      var u8 = new Uint8Array(word1.sigBytes + word2.sigBytes);

      //var i=0;
      for (var i = 0; i < word1.sigBytes; i++) {
        var byte = (uw1[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
        u8[i] = byte;
      }
      for (var j = 0; j < word2.sigBytes; j++) {
        var byte = (uw2[j >>> 2] >>> (24 - (j % 4) * 8)) & 0xff;
        u8[i + j] = byte;
      }
      return CryptoJS.enc.u8array.parse(u8);
    }
  },

  dosave(value, type, name) {
    var blob;
    if (typeof window.Blob == "") {
      blob = new Blob([value], {type: type});
    } else {
      var BlobBuilder = window.BlobBuilder || window.MozBlobBuilder || window.WebKitBlobBuilder || window.MSBlobBuilder;
      var bb = new BlobBuilder();
      bb.append(value);
      blob = bb.getBlob(type);
    }
    var URL = window.URL || window.webkitURL;
    var bloburl = URL.createObjectURL(blob);
    var anchor = document.createElement("a");
    if ('download' in anchor) {
      anchor.style.visibility = "hidden";
      anchor.href = bloburl;
      anchor.download = name;
      document.body.appendChild(anchor);
      var evt = document.createEvent("MouseEvents");
      evt.initEvent("click", true, true);
      anchor.dispatchEvent(evt);
      document.body.removeChild(anchor);
    } else if (navigator.msSaveBlob) {
      navigator.msSaveBlob(blob, name);
    } else {
      location.href = bloburl;
    }
  },

  Str2Bytes(str) {
    var pos = 0;
    var len = str.length;
    if (len % 2 != 0) {
      return null;
    }
    len /= 2;
    var hexA = new Array();
    for (var i = 0; i < len; i++) {
      var s = str.substr(pos, 2);
      var v = parseInt(s, 16);
      hexA.push(v);
      pos += 2;
    }
    return hexA;
  },

  Bytes2Str(arr) {
    var str = "";
    for (var i = 0; i < arr.length; i++) {
      var tmp = arr[i].toString(16);
      if (tmp.length == 1) {
        tmp = "0" + tmp;
      }
      str += tmp;
    }
    return str;
  }
}
